package io.github.uicdb.et.client;

import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec3;
import org.joml.Matrix4f;
import org.joml.Vector3f;


public class FDRenderHelper {
    /**
     * 在指定坐标渲染有材质的项目
     * @param matrixStack PoseStack
     * @param partialTick partialTick
     * @param pos 坐标
     * @param renderType 渲染类型，其中通过设置ResourceLocation指定了材质
     * @param onLevelRenderer 具体渲染内容
     * @see SimpleRenderType
     * @see RenderType
     */
    public  static void renderOnPosition(PoseStack matrixStack, float partialTick, Vector3f pos, RenderType renderType, onLevelRenderer onLevelRenderer){
        var bufferSource= Minecraft.getInstance().renderBuffers().bufferSource();
        float px = pos.x();
        float py = pos.y();
        float pz = pos.z();
        VertexConsumer builder = bufferSource.getBuffer(renderType);
        matrixStack.pushPose();
        bindMainCameraPos(matrixStack,px,py,pz);
        Matrix4f matrix = matrixStack.last().pose();
        //render
        onLevelRenderer.onRenderer(matrixStack,builder,matrix,partialTick);

        matrixStack.popPose();

        RenderSystem.disableDepthTest();
        bufferSource.endBatch(renderType);
    }

    /**
     * 绑定相机相对位置
     * @param stack PoseStack
     * @see FDRenderHelper
     */
    public static void bindMainCameraPos(PoseStack stack, double x, double y, double z){
        var camera=Minecraft.getInstance().gameRenderer.getMainCamera();
        Vec3 projectedView = camera.getPosition();
        stack.translate(x-projectedView.x,y -projectedView.y,z -projectedView.z);
    }
    /**
     * 绑定相机相对位置
     * @param stack PoseStack
     * @see FDRenderHelper
     */
    public static void bindEntityCameraPos(PoseStack stack, double x, double y, double z){
        var camera=Minecraft.getInstance().getBlockEntityRenderDispatcher().camera;
        Vec3 projectedView = camera.getPosition();
        stack.translate(x-projectedView.x,y -projectedView.y,z -projectedView.z);
    }
    public static void bindEntityPos(PoseStack stack, Entity entity,float p){
        var pos=entity.getPosition(p);
        stack.translate(pos.x,pos.y,pos.z);
    }

    public interface onLevelRenderer {
        void onRenderer(PoseStack poseStack, VertexConsumer buffer, Matrix4f matrix,float partialTick);
    }
}
